package handler

import (
	"common"
	"common/biz"
	"common/logs"
	"context"
	"core/repo"
	"core/service"
	"encoding/json"
	"framework/remote"
	"hall/logic"
	"hall/models/request"
	"strconv"
)

type InvestmentHandler struct {
	base             *BaseHandler
	warehouseService *service.WarehouseService
	userService      *service.UserService
	im               *logic.InvestmentManager
}

func (h *InvestmentHandler) InvestmentCore(session *remote.Session, msg []byte) any {
	logs.Info("[investmentHandler] InvestmentCore msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[investmentHandler] InvestmentCore err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := h.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	ctx := context.TODO()
	user, err := h.userService.FindUserByUid(ctx, uint(uid))
	if err != nil {
		return common.F(biz.SqlError)
	}
	h.im.AddUser(user)
	data := h.warehouseService.GetInvestmentCore(ctx, uint(uid))
	return common.S(data)
}

func (h *InvestmentHandler) InvestmentExchange(session *remote.Session, msg []byte) any {
	logs.Info("[investmentHandler] InvestmentExchange msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[investmentHandler] InvestmentExchange err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := h.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	var req request.InvestmentExchange
	if err := json.Unmarshal(msg, &req); err != nil {
		logs.Error("[investmentHandler]用户%d InvestmentExchange err:缺少参数 req=%v,err=%v", uid, req, err)
		return common.F(biz.RequestDataError)
	}
	ctx := context.TODO()
	user, err := h.userService.FindUserByUid(ctx, uint(uid))
	if err != nil {
		logs.Error("[investmentHandler]用户%d InvestmentExchange err:缺少参数 req=%v,dbErr=%v", uid, req, err)
		return common.F(biz.SqlError)
	}
	errs := h.im.Exchange(ctx, user, &req, session)
	if errs != nil {
		return common.F(errs)
	}
	return common.S(nil)
}

func (h *InvestmentHandler) InvestmentOut(session *remote.Session, msg []byte) any {
	logs.Info("[investmentHandler] InvestmentOut msg:%v", string(msg))
	uid, _ := strconv.Atoi(session.GetUid())
	if uid <= 0 {
		logs.Error("[investmentHandler] InvestmentOut err:未获取到UID")
		return common.F(biz.InvalidUsers)
	}
	if err := h.base.Login(nil, uint(uid), session.GetSid()); err != nil {
		return common.F(err)
	}
	h.im.Out(uint(uid))
	return common.S(nil)
}

func NewInvestmentHandler(r *repo.Manager, m *logic.InvestmentManager) *InvestmentHandler {
	return &InvestmentHandler{
		base:             NewBaseHandler(r),
		warehouseService: service.NewWarehouseService(r),
		userService:      service.NewUserService(r),
		im:               m,
	}
}
